package impl;

import db.Connector;
import db.Db;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Connection;
import java.util.*;
import model.User;
import settings.Settings;
import utils.Util;

/**
 *
 * @author Fedor, Max
 */
public class UserImpl {

    private static UserImpl instance = UserImpl.getInstance();

    public static UserImpl getInstance() {
        if (instance == null) {
            instance = new UserImpl();
        }
        return instance;
    }
    /**
     * PREFIX для того, что бы не произошло совпадения имён
     */
    private final String BY_ID = "SELECT p.* "
            + " FROM players p where id=?";
    private final String BY_SNET_ID = "SELECT p.* "
            + " FROM players p where snet_id=?";
    private final String USER_SAVE = "insert into players(id) values(?,)";

    /**
     * Создает нового пользователя в БД
     *
     * @param user
     * @return
     */
    public boolean insertUser(User user) {
        boolean res = false;
        if (user == null) {
            return res;
        }
        Connection connection = null;
        PreparedStatement ps = null;
        ResultSet rs = null;
        try {
            connection = Connector.getConnection();
            try {
                ps = connection.prepareStatement(USER_SAVE);
                res = ps.executeUpdate() == 1;
            } catch (SQLException e) {
                System.out.println("SQLException: " + e + " sql: " + USER_SAVE);
            } finally {
                Db.closeConnection(connection, ps, rs);
            }
        } catch (Exception e) {
            System.out.println("SQLException: " + e);
        }
        return res;
    }

    public User getById(int id) {
        User res = null;
        Connection connection = null;
        PreparedStatement ps = null;
        ResultSet rs = null;
        try {
            connection = Connector.getConnection();
            try {
                ps = connection.prepareStatement(BY_ID);
                ps.setInt(1, id);
                rs = ps.executeQuery();
                if (rs.next()) {
                    res = getByRs(rs);
                }
            } catch (SQLException e) {
                System.out.println("SQLException: " + e + " sql: " + BY_ID);
            } finally {
                Db.closeConnection(connection, ps, rs);
            }
        } catch (Exception e) {
            System.out.println("Exception: " + e);
        }
        return res;
    }

    public User getByRs(ResultSet rs) throws SQLException {
        User user = new User();
        user.setId(rs.getInt("id"));
        user.setFirstname(rs.getString("firstname"));
        user.setSurname(rs.getString("surname"));
        user.setSnetId(rs.getString("snet_id"));
        user.setSexId(rs.getInt("sex_id"));
        return user;
    }
}
